<template>
	<view class="content">
		<view class="gradient-bg">
			<!-- 渐变背景 -->
			<view class="list-card-wrap">
				<view class="flex-row-between" style="margin-bottom: 8rpx;">
					<view class="flex-row">
						<text class="white-text font-24">单据编号</text>
						<text class="white-text font-24" style="margin-left: 20rpx;">{{taskInfo.no}}</text>
					</view>
				</view>
				<view class="list-card">
					<view class="">
						<text class="black-text-34">{{taskInfo.supplierName}}</text>
					</view>
					<view class="content-blue flex-row">
						<view class="flex-column flex1">
							<text class="gray-text">到货总数</text>
							<text class="black-text">{{taskInfo.totalQty}}</text>
						</view>
						<view class="split"></view>
						<view class="flex-column flex1">
							<text class="gray-text">收货总数</text>
							<text class="black-text">{{taskInfo.checkTotalQty || 0}}</text>
						</view>
					</view>
				</view>
			</view>
			<view class="s-input-wrap">
				<view class="s-input-box flex-row-between">
					<text class="gray-text font-30">托盘号</text>
					<input auto-focus="true" @confirm="checkTrayNo" v-model="trayNo" class="s-input flex1" placeholder="请输入托盘号" />
					<image v-if="trayNo" class="s-input-icon clear-icon" src="/static/images/clear.png" @click="trayNo = ''"></image>
					<image class="s-input-icon" src="/static/images/scan.png"></image>
				</view>
			</view>
			<view class="s-input-wrap">
				<view class="s-input-box flex-row-between">
					<text class="gray-text font-30">物料编号</text>
					<input v-model="productNo" @confirm="handleScan" class="s-input flex1"
						placeholder="请输入或扫描物料编号" />
					<image v-if="productNo" class="s-input-icon clear-icon" src="/static/images/clear.png" @click="clearField"></image>
					<image class="s-input-icon" src="/static/images/scan.png"></image>
					
				</view>
				<view class="s-input-box flex-row-between">
					<text class="gray-text font-30">物料名称</text>
					<text class="black-text font-30">{{product.productName}}</text>
				</view>
				<view class="s-input-box flex-row-between">
					<text class="gray-text font-30">需求数量</text>
					<text class="black-text font-30">{{product.arrivalQty}}</text>
				</view>
				<view class="s-input-box flex-row-between">
					<text class="gray-text font-30">已收数量</text>
					<text class="black-text font-30">{{ product.quantityReceived  }}</text>
				</view>
				<view class="s-input-box flex-row">
					<text class="gray-text font-30">收货数量</text>
					<input @input="setNum" type="number" v-model="product.resultQty" class="s-input flex1"
						placeholder="请输入收货数量" />
					<text class="gray-text font-30">{{productObj.cgUnitName}}</text>
				</view>
				<view class="s-input-box flex-row-between">
					<text class="gray-text font-30">生产日期</text>
					<picker mode="date" :value="productDate" @change="bindProductDateChange">
						<view class="black-text font-30">{{productDate?productDate:'请选择生产日期'}}</view>
					</picker>
					<!--<text class="black-text font-30">{{product.productDate}}</text>-->
				</view>
				<view class="s-input-box flex-row-between">
					<text class="gray-text font-30">有效期</text>
					<text class="gray-text font-30">{{productObj.qualityGuaranteePeriodTemp}}</text>
				</view>
			</view>

			<view @click="addDetail" class="botton p-botton font-30"
				style="height: 92rpx; line-height:92rpx;margin: 0 25rpx;">
				收货
			</view>
		</view>

		<view class="table-wrap" style="padding-bottom: 100rpx;">
			<view class="flex-row-start" style="margin: 10rpx 0;">
				<text class="gray-text font-24">收货纪录</text>
				<uni-icons type="top" size="14" style="color: #8997A8;"></uni-icons>
			</view>
			<zb-table @dele="deleteDetail" :show-header="true" :columns="detailColumns" :fit="true" :border="true"
				:data="detailData">
			</zb-table>
		</view>

		<view class="content-list-total flex-row-between">
			<text class="gray-text">合计:</text>
			<view class="flex-row">
				<text class="gray-text">共<text class="blue-text font-38">{{taskInfo.checkTotalQty||0}}</text>件</text>
				<view @click="completeTask" class="botton p-botton">完成</view>
			</view>
		</view>

	</view>
</template>

<script>
	import {
		validNum,
		addDaysToDate,
		validateTrayCode
	} from "@/utils/common"
	import {
		getTaskInfoById,
		getBillReceiveDetailList,
		getBillProductList,
		addReceiveDetail,
		delByReceiveDetail,
		complete,
		saveBarcode,
		getTaskInfoByCode
	} from "./api"


	export default {
		onLoad(option) {
			this.taskId = option.id;
		},
		created() {
			this.tableHeiht = this.windowHeight - 420;
			this.getTaskDetail();
		},
		data() {
			return {
				computedQtyTxtStatus:'',
				productObj:{},
				productNo: "",
				tableHeiht: 0,
				date: '',
				warehouse: '',
				taskId: '',
				taskInfo: {},
				code: '',
				number: 12,
				detailData: [],
				productData: [],
				// selectStartDate:false,
				// selectEndDate:false,
				product: {},
				trayNo: '',
				productDate: '',
				validDate: '',
				detailColumns: [{
						type: 'index',
						label: '序号',
						align: 'center',
						width: 40
					},
					{
						name: 'trayNo',
						label: '托盘号',
						fixed: false,
						emptyString: '--'
					},
					{
						name: 'productNo',
						label: '物料编号',
						fixed: false,
						emptyString: '--'
					},
					{
						name: 'productName',
						label: '物料',
						sorter: false,
					},
					{
						name: 'batchNo',
						label: '批次号',
						sorter: false,
					},
					{
						name: 'qty',
						label: '数量'
					},
					{
						name: 'productionDate',
						label: '生产日期'
					},
					{
						name: 'expiryDate',
						label: '有效日期'
					},
					{
						name: 'operation',
						type: 'operation',
						label: '操作',
						renders: [{
							name: '/static/images/delete.png',
							type: 'icon',
							func: "dele",
							style: "width:24rpx;height:28rpx"
						}, ],
					},
				],

			}
		},
		computed: {

		},
		methods: {
			checkTrayNo(){
			if (!validateTrayCode(this.trayNo)) {
				this.trayNo = ''
				this.$modal.msg("托盘号格式错误")
			}
		},
			clearField(){
				this.productNo = ''
				this.clearObjInfo()
			},
			clearMaterialInfo(){
				this.productObj  = ''
				this.product = ''
				this.productDate = ''
			},
			handleScan() {
				getTaskInfoByCode(this.productNo).then(res => {
					if (res.code == 200) {
						this.pTipName = res.data.productName
						this.clearMaterialInfo()
						this.productObj = res.data
						// debugger
						if(res.data){
							this.bindPickerProductTwo(this.productObj.productNo)
						}else{
							// this.$modal.msg("此物料不在订单中");
							this.$modal.confirmClose(`商品『${this.pTipName}』不在订单${this.taskInfo.no}中`);
						}
					}else {
						res.msg && this.$modal.confirmClose(res.msg)
					}
				})
			},
			clearObjInfo(){
				this.productDate = '';
				this.productNo = '';
				this.product = {};
				this.productObj = {}
			},
			bindPickerProductTwo(no) {
				if (!this.productData || this.productData.length == 0) {
					return;
				}
				
				console.log(this.productData,'this.productData')
				
				let o = this.productData.find(el => el.productNo == no)
				if(!o){
					this.clearObjInfo()
					// this.$modal.msg("此物料不在订单中");
					this.$modal.confirmClose(`商品『${this.pTipName}』不在订单${this.taskInfo.no}中`);
					return
				}
				this.product = o
				this.product.arrivalQty =   this.computedQtyTxt(this.product.qty)//   需求数量
				
				this.product.quantityReceived =  this.computedQtyTxt(this.getQuantityReceived());  //已收数量
				// this.product.qty = this.computedQtyTxt(this.product.qty - this.getQuantityReceived(),'noUni')  //收货数量
				// if(this.product.qty < 0){
				// 	this.product.qty = 0
				// }
			},
			computedQtyTxt(num,type){
				try {
					if (!this.productObj?.productNo || !this.productData?.length) {
						return 0;
					}
					const product = this.productData.find(el => el.productNo === this.productObj.productNo);
					
					if (!product?.qty) {
						return 0;
					}

					const cgPsConver = Number(this.productObj.cgPsConver) || 0;
					const ylPsConver = Number(this.productObj.ylPsConver) || 0;
					const conversionRate = cgPsConver * ylPsConver;

					if (!conversionRate) {
						return num;
					}
					
					let cn  = 0
					if(type =='noUni'){
						cn = Math.floor(num / conversionRate)
					}else{
						cn = Math.floor(num / conversionRate) + this.productObj.cgUnitName;
					}
					return cn
				} catch (error) {
					console.error('Error in computedQtyTxt:', error);
					return 0;
				}
			},
			//获取已收数量
			getQuantityReceived() {
				let productNum = parseFloat(0)
				this.detailData.forEach(item => {
					if (item.productNo == this.product.productNo) {
						productNum += parseFloat(item.qty)
					}
				})
				return productNum
			},
			// 数量校验			
			setNum(e) {
				this.$set(this.product, 'qty', validNum(e))
			},
			bindProductDateChange(e) {
				this.productDate = e.detail.value
				this.product.batchNo = addDaysToDate(this.productDate,0,1)
				this.productObj.qualityGuaranteePeriodTemp = addDaysToDate(this.productDate, this.productObj.qualityGuaranteePeriod)
			},
			bindValidDateChange(e) {
				this.validDate = e.detail.value
			},
			getTaskDetail() {
				getTaskInfoById(this.taskId).then(res => {
					if (res.code == 200) {
						this.taskInfo = res.data
						// 继续查询收货任务明细
						getBillReceiveDetailList({
							billNo: this.taskInfo.no,
							pageNum: 1,
							pageSize: 9999,
						}).then(res => {
							if (res.code == 200) {
								this.productData = res.rows;
							}
						})
						this.getBillProductList()
					}else {
						res.msg && this.$modal.confirmClose(res.msg)
					}
				})
			},
			// 查询收货清单(物料列表)
			getBillProductList() {
				getBillProductList({
					billNo: this.taskInfo.no,
					pageNum:1,
					pageSize: 999
				}).then(res => {
					if (res.code == 200) {
						this.detailData = res.rows;
					}else {
						res.msg && this.$modal.confirmClose(res.msg)
					}
				})
			},
			// 校验收货数量不能大于需求数量
			validQty() {
				let productNum = parseFloat(this.product.qty)
				this.detailData.forEach(item => {
					if (item.productNo == this.product.productNo) {
						productNum += parseFloat(item.qty)
					}
				})
				if (productNum > this.product.arrivalQty) {
					return false
				}
				return true
			},
			// 加入收货单
			addDetail() {
				if (!this.trayNo) {
					this.$modal.msg("请输入托盘号");
					return;
				}
				if (!this.product.productNo) {
					this.$modal.msg("请先选择物料");
					return;
				}
				if (!this.validQty()) {
					this.$modal.msg("物料收货数量大于需求数量");
					return;
				}
				if (!this.productDate) {
					this.$modal.msg("请选择生产日期");
					return;
				}
				let _qty =  this.productObj?.cgPsConver ?( Number(this.product.resultQty)*Number(this.productObj?.cgPsConver)*Number(this.productObj.ylPsConver)) : this.product.resultQty
				let obj = {
					billNo: this.taskInfo.no,
					trayNo: this.trayNo,
					productNo: this.product.productNo,
					productName: this.product.productName,
					productUnit: this.product.productUnit,
					qty: _qty,
					batchNo: this.product.batchNo,
					productDate: this.productDate,
					validDate: this.productObj.qualityGuaranteePeriodTemp
				}
				this.$modal.loading("加载中...")
				addReceiveDetail(obj).then(res => {
					this.$modal.closeLoading()
					if (res.code == 200) {
						this.$modal.msgSuccess("操作成功");
						let barcodeObj = {
							productNo: this.product.productNo,
							quantity: this.product.qty
						}
						this.getTaskDetail();
					}else {
							res.msg && this.$modal.confirmClose(res.msg)
					}
					this.clearObjInfo()
				})
			},
			deleteDetail(row) {
				this.$modal.confirm('是否确认删除数据').then(() => {
					this.$modal.loading("加载中...")
					delByReceiveDetail(row).then(res => {
						this.$modal.closeLoading()
						if (res.code == 200) {
							this.$modal.msgSuccess("操作成功");
							this.getTaskDetail();
						}else {
							res.msg && this.$modal.confirmClose(res.msg)
						}
					})
				})
			},
			completeTask() {
				let confimText = '是否确认完成？'
				if (this.taskInfo.checkTotalQty < this.taskInfo.totalQty) {
					confimText = '收货总数小于到货总数,是否确认完成？'
				}
				this.$modal.confirm(confimText).then(() => {
					this.$modal.loading("加载中...")
					complete({
						no: this.taskInfo.no
					}).then(res => {
						this.$modal.closeLoading()
						if (res.code == 200) {
							this.$modal.msgSuccess("操作成功");
							// this.getTaskDetail();
							// 延迟1秒跳转
							uni.$emit('refreshList', {
								msg: '页面更新'
							})
							setTimeout(() => {
								uni.navigateBack();
							}, 1000);
						}else {
							res.msg && this.$modal.confirmClose(res.msg)
						}
					})
				})
			},
		}
	}
</script>

<style>
	page {
		background-color: #F8F8F8;
	}
</style>
<style scoped>

</style>